package com.yu.Demo03;

import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ShareResource {

    //定义标志位
    private int flag = 1; //线程A = 1，线程B = 2，线程C = 3
    private Lock lock = new ReentrantLock();
    Condition c1 = lock.newCondition();
    Condition c2 = lock.newCondition();
    Condition c3 = lock.newCondition();

    public void print5 (int pool) throws InterruptedException {
        lock.lock();
        try {
            while (flag!=1){
                c1.await();
            }
            for (int i = 1; i <= 5; i++) {
                System.out.println(Thread.currentThread().getName() + "打印A，第" + pool + "轮第"+i+"次开始");
            }
            flag = 2;
            c2.signal();
        }catch (Exception e){

        }finally {
            lock.unlock();
        }
    }

    public void print10 (int pool) throws InterruptedException {
        lock.lock();
        try {
            while (flag!=2){
                c2.await();
            }
            for (int i = 1; i <=10 ; i++) {
                System.out.println(Thread.currentThread().getName() + "打印B，第" + pool +"轮第"+i+"次开始");
            }
            flag = 3;
            c3.signal();
        }catch (Exception e){

        }finally {
            lock.unlock();
        }
    }

    public void print15 (int pool) throws InterruptedException {
        lock.lock();
        try {
            while (flag!=3){
                c3.await();
            }
            for (int i = 1; i <=15 ; i++) {
                System.out.println(Thread.currentThread().getName() + "打印C，第" + pool +"轮第"+i+"次开始");
            }
            flag = 1;
            c1.signal();
        }catch (Exception e){

        }finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        ShareResource resource = new ShareResource();
        new Thread(()->{
            try {
                for (int i = 1; i <=10; i++) {
                    resource.print5(i);
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"A线程").start();


        new Thread(()->{
            try {
                for (int i = 1; i <= 10; i++) {
                    resource.print10(i);
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"B线程").start();


        new Thread(()->{
            try {
                for (int i = 1; i <=10 ; i++) {
                    resource.print15(i);
                }

            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        },"C线程").start();
    }
}
